package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j@NoArgsConstructor
public class ExcelDictDTOLister extends AnalysisEventListener<ExcelDictDTO> {
    private DictMapper dictMapper;
    //设置每次插入5条数据
    public static final int BATCH_COUNT = 5;
    //创建数据列表
    private List<ExcelDictDTO> dictList = new ArrayList<>();

    /**
     * 构造器注入
     * @param dictMapper
     */
    public ExcelDictDTOLister(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO excelDictDTO, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}" ,excelDictDTO);
        dictList.add(excelDictDTO);
        if (dictList.size()>BATCH_COUNT){
            System.out.println("dictList = " + dictList);
            //调用mapper的save方法
            saveData();
            dictList.clear();
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //当最后的记录不足5条,最终一次性收尾存储数据
        if (dictList.size() != 0 ) {
            saveData();
        }
        log.info("所有数据解析完成了....");
    }

    
    public  void saveData() {
        log.info("{}条数据存储到数据库",dictList.size());
        //调用mapper的save方法
        dictMapper.insertBatch(dictList);

    }
}
